758E - Broken Tree - CodeForces Solution


dfs and similar dp graphs greedy trees *2600

Please click on ads to support us..

C++ Code:

#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N = 2e5 + 5;
int n, head[N], cnt, S[N];
struct Edge {
	int to, nxt, weight, price, delta; 
} edges[N<<1]; 
LL dfs(int now, int pre) {
	LL sum = 0;
	for(int i = head[now]; i; i = edges[i].nxt)
		if(edges[i].to != pre) {
			LL res = dfs(edges[i].to, now);
			if(res > edges[i].price) {
				puts("-1");
				exit(0);
			}
			edges[i].delta = min(edges[i].price - (int)res, edges[i].weight - 1);
			sum += res + edges[i].weight - edges[i].delta;
		}
	return S[now] = sum;
}
LL dfs2(int now, int pre, LL lim) {
	LL res = 0;
	for(int i = head[now]; i; i = edges[i].nxt)
		if(edges[i].to != pre) {
			int add = min((LL)edges[i].delta, lim);
			edges[i].delta -= add;
			lim -= add;
			res += add;
			LL x = dfs2(edges[i].to, now, min(lim, (LL)edges[i].price - edges[i].delta - S[edges[i].to]));
			res += x;
			lim -= x;
		}
	return res;
}
int main() {
	scanf("%d", &n);
	for(int i = 1; i < n; ++i) {
		int u, v, weight, price;
		scanf("%d%d%d%d", &u, &v, &weight, &price);
		edges[++cnt] = (Edge){v, head[u], weight, price}; 
		head[u] = cnt;
		edges[++cnt] = (Edge){u, head[v], weight, price}; 
		head[v] = cnt;
	}
    dfs(1, 0);
    printf("%d\n", n);
    dfs2(1, 0, 1e18);
    for(int i = 1; i <= cnt; i += 2)
		printf("%d %d %d %d\n", edges[i+1].to, edges[i].to, edges[i].weight - edges[i].delta, edges[i].price - edges[i].delta); // Переименовал e в edges
	return 0;
}/*1695073795.3099775*/


Comments

Submit
0 Comments
More Questions

544B - Sea and Islands
152B - Steps
1174D - Ehab and the Expected XOR Problem
1511A - Review Site
1316A - Grade Allocation
838A - Binary Blocks
1515D - Phoenix and Socks
1624D - Palindromes Coloring
1552F - Telepanting
1692G - 2Sort
1191A - Tokitsukaze and Enhancement
903A - Hungry Student Problem
52B - Right Triangles
1712A - Wonderful Permutation
1712D - Empty Graph
1712B - Woeful Permutation
1712C - Sort Zero
1028B - Unnatural Conditions
735B - Urbanization
746C - Tram
1278B - A and B
1353D - Constructing the Array
1269C - Long Beautiful Integer
1076A - Minimizing the String
913C - Party Lemonade
1313A - Fast Food Restaurant
681A - A Good Contest
1585F - Non-equal Neighbours
747A - Display Size
285A - Slightly Decreasing Permutations